// Simple theme store without external dependencies
// - colorTheme: 'light' | 'dark' | 'system'
// - fileIconTheme: 'vscode' | 'minimal' | 'none'
// - productIconTheme: 'codicon' | 'lucide' | 'feather'
// - customColors: 自定义颜色配置

const subscribers = new Set();

export const theme = {
  colorTheme: 'system',
  fileIconTheme: 'vscode',
  productIconTheme: 'codicon',
  // 自定义颜色配置
  customColors: {
    light: {
      accent: '#3b82f6',
      accentContrast: '#ffffff',
      panelBg: '#ffffff',
      panelFg: '#0f172a',
      appBg: '#f8fafc',
      appFg: '#0f172a',
    },
    dark: {
      accent: '#60a5fa',
      accentContrast: '#0a0a0a',
      panelBg: '#222426',
      panelFg: '#d4d4d4',
      appBg: '#222426',
      appFg: '#d4d4d4',
    }
  },
  // 界面配置
  interface: {
    fontSize: 'medium', // 'small' | 'medium' | 'large'
    density: 'comfortable', // 'compact' | 'comfortable' | 'spacious'
    borderRadius: 'medium', // 'none' | 'small' | 'medium' | 'large'
    animations: true,
  }
};

export function initTheme() {
  try {
    // 加载基本主题设置
    const saved = (typeof localStorage !== 'undefined') ? localStorage.getItem('colorTheme') : null;
    if (saved) {
      theme.colorTheme = saved;
    }
    
    // 加载自定义颜色配置
    const customColors = (typeof localStorage !== 'undefined') ? localStorage.getItem('customColors') : null;
    if (customColors) {
      try {
        const parsed = JSON.parse(customColors);
        theme.customColors = { ...theme.customColors, ...parsed };
      } catch {}
    }
    
    // 加载界面配置
    const interfaceConfig = (typeof localStorage !== 'undefined') ? localStorage.getItem('interfaceConfig') : null;
    if (interfaceConfig) {
      try {
        const parsed = JSON.parse(interfaceConfig);
        theme.interface = { ...theme.interface, ...parsed };
      } catch {}
    }
    
    // 加载其他主题设置
    const fileIconTheme = (typeof localStorage !== 'undefined') ? localStorage.getItem('fileIconTheme') : null;
    if (fileIconTheme) theme.fileIconTheme = fileIconTheme;
    
    const productIconTheme = (typeof localStorage !== 'undefined') ? localStorage.getItem('productIconTheme') : null;
    if (productIconTheme) theme.productIconTheme = productIconTheme;
    
    applyColorTheme(theme.colorTheme);
    applyCustomColors();
    applyInterfaceConfig();
    return;
  } catch {}
  applyColorTheme(theme.colorTheme);
  applyCustomColors();
  applyInterfaceConfig();
}

export function subscribe(listener) {
  subscribers.add(listener);
  return () => subscribers.delete(listener);
}

function notify() {
  subscribers.forEach((fn) => {
    try { fn(theme); } catch {}
  });
}

export function setColorTheme(mode) {
  theme.colorTheme = mode;
  applyColorTheme(mode);
  try { if (typeof localStorage !== 'undefined') localStorage.setItem('colorTheme', String(mode)); } catch {}
  notify();
}

function applyColorTheme(mode) {
  const root = document.documentElement;
  const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
  const isDark = mode === 'dark' || (mode === 'system' && prefersDark);
  root.classList.toggle('dark', !!isDark);
  
  // 在主题切换后应用自定义颜色
  setTimeout(() => {
    applyCustomColors();
  }, 0);
}

export function setFileIconTheme(name) {
  theme.fileIconTheme = name;
  try { if (typeof localStorage !== 'undefined') localStorage.setItem('fileIconTheme', String(name)); } catch {}
  notify();
}

export function setProductIconTheme(name) {
  theme.productIconTheme = name;
  try { if (typeof localStorage !== 'undefined') localStorage.setItem('productIconTheme', String(name)); } catch {}
  notify();
}

// 自定义颜色设置
export function setCustomColor(mode, colorKey, value) {
  if (!theme.customColors[mode]) {
    theme.customColors[mode] = {};
  }
  theme.customColors[mode][colorKey] = value;
  try { 
    if (typeof localStorage !== 'undefined') {
      localStorage.setItem('customColors', JSON.stringify(theme.customColors));
    }
  } catch {}
  applyCustomColors();
  notify();
}

// 界面配置设置
export function setInterfaceConfig(key, value) {
  theme.interface[key] = value;
  try {
    if (typeof localStorage !== 'undefined') {
      localStorage.setItem('interfaceConfig', JSON.stringify(theme.interface));
    }
  } catch {}
  applyInterfaceConfig();
  notify();
}

// 应用自定义颜色
function applyCustomColors() {
  const root = document.documentElement;
  const isDark = root.classList.contains('dark');
  const colors = isDark ? theme.customColors.dark : theme.customColors.light;
  
  // 应用自定义颜色
  if (colors.accent) root.style.setProperty('--accent', colors.accent);
  if (colors.accentContrast) root.style.setProperty('--accent-contrast', colors.accentContrast);
  if (colors.panelBg) root.style.setProperty('--panel-bg', colors.panelBg);
  if (colors.panelFg) root.style.setProperty('--panel-fg', colors.panelFg);
  if (colors.appBg) root.style.setProperty('--app-bg', colors.appBg);
  if (colors.appFg) root.style.setProperty('--app-fg', colors.appFg);
}

// 应用界面配置
function applyInterfaceConfig() {
  const root = document.documentElement;
  const config = theme.interface;
  
  // 字体大小
  const fontSizeMap = {
    small: '12px',
    medium: '14px',
    large: '16px'
  };
  if (fontSizeMap[config.fontSize]) {
    root.style.setProperty('--base-font-size', fontSizeMap[config.fontSize]);
  }
  
  // 密度
  const densityMap = {
    compact: '0.8',
    comfortable: '1.0',
    spacious: '1.2'
  };
  if (densityMap[config.density]) {
    root.style.setProperty('--ui-density', densityMap[config.density]);
  }
  
  // 边框圆角
  const borderRadiusMap = {
    none: '0px',
    small: '2px',
    medium: '4px',
    large: '8px'
  };
  if (borderRadiusMap[config.borderRadius]) {
    root.style.setProperty('--border-radius', borderRadiusMap[config.borderRadius]);
  }
  
  // 动画
  root.style.setProperty('--animations-enabled', config.animations ? '1' : '0');
}

// Icon registry: product icons
const codicon = {
  sidebar: (cls='') => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" class="${cls}"><rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M16 5v14"/></svg>`,
  refresh: (cls='') => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" class="${cls}"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9A9 9 0 0 1 12 3a9 9 0 0 1 8.49 6"/><path d="M20.49 15A9 9 0 0 1 12 21a9 9 0 0 1-8.49-6"/></svg>`,
  send: (cls='') => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" class="${cls}"><path d="M22 2L11 13"/><path d="M22 2L15 22L11 13L2 9L22 2Z"/></svg>`,
  panelLeft: (cls='') => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" class="${cls}"><rect x="3.5" y="4.5" width="17" height="15" rx="2"/><path d="M8 5v14"/></svg>`,
  settings: (cls='') => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" class="${cls}"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 8.1 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82A1.65 1.65 0 0 0 2 12a1.65 1.65 0 0 0 1.51-1V11a2 2 0 1 1 0-4v.09A1.65 1.65 0 0 0 4.6 8.6a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82c.14.54.52.99 1.02 1.25.5.26 1.1.26 1.6 0 .5-.26.88-.71 1.02-1.25A1.65 1.65 0 0 0 19.4 15z"/></svg>`,
};

export function getProductIcon(name, cls='') {
  const set = theme.productIconTheme;
  // currently only codicon map provided; could switch by set
  return (codicon[name] || (() => ''))(cls);
}


